package com.yanxinim.cn.store;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.store.adapter.GoodsImageAdapter;
import com.yanxinim.cn.store.adapter.TextAdapter;
import com.yanxinim.cn.ui.base.BaseActivity;
import com.yanxinim.cn.util.JsonTool;
import com.yanxinim.cn.util.SpacesItemDecoration;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.view.MyGridView;
import com.yanxinim.cn.view.TipDialog;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class StoreGoodsDetailsActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_store_car)
    ImageView ivStoreCar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_market_price)
    TextView tvMarketPrice;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_goods_flag)
    TextView tvGoodsFlag;
    @BindView(R.id.tv_goods_tag)
    TextView tvGoodsTag;
    @BindView(R.id.tv_goods_details)
    TextView tvGoodsDetails;
    @BindView(R.id.tv_miaoshu_level)
    TextView tvMiaoshuLevel;
    @BindView(R.id.tv_miaoshu_flag)
    TextView tvMiaoshuFlag;
    @BindView(R.id.tv_zhiliang_level)
    TextView tvZhiliangLevel;
    @BindView(R.id.tv_zhiliang_flag)
    TextView tvZhiliangFlag;
    @BindView(R.id.tv_wuliu_level)
    TextView tvWuliuLevel;
    @BindView(R.id.tv_wuliu_flag)
    TextView tvWuliuFlag;
    @BindView(R.id.radio_goods_details)
    RadioButton radioGoodsDetails;
    @BindView(R.id.radio_goods_comment)
    RadioButton radioGoodsComment;
    @BindView(R.id.rv_goods_images)
    RecyclerView rvGoodsImages;
    @BindView(R.id.rv_goods_comment)
    RecyclerView rvGoodsComment;
    @BindView(R.id.ll_bottom_line)
    LinearLayout llBottomLine;
    @BindView(R.id.tv_cart_num)
    TextView tvCartNum;
    @BindView(R.id.rl_add_cart)
    RelativeLayout rlAddCart;
    @BindView(R.id.tv_add_cart)
    TextView tvAddCart;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.view_choose)
    View viewChoose;
    @BindView(R.id.iv_close_choose)
    ImageView ivCloseChoose;
    @BindView(R.id.iv_goods_image)
    ImageView ivGoodsImage;
    @BindView(R.id.tv_goods_name2)
    TextView tvGoodsName2;
    @BindView(R.id.tv_goods_price2)
    TextView tvGoodsPrice2;
    @BindView(R.id.gv_spec)
    MyGridView gvSpec;
    @BindView(R.id.ll_choose)
    LinearLayout llChoose;
    @BindView(R.id.rl_choose)
    RelativeLayout rlChoose;
    @BindView(R.id.tv_minus_num)
    TextView tvMinusNum;
    @BindView(R.id.tv_goods_num)
    TextView tvGoodsNum;
    @BindView(R.id.tv_add_num)
    TextView tvAddNum;
    @BindView(R.id.tv_choose_commit)
    TextView tvChooseCommit;
    int goodsNum = 1;
    @BindView(R.id.radio_group_details)
    RadioGroup radioGroupDetails;
    @BindView(R.id.rv_goods_desc_nothing)
    ImageView rvGoodsDescNothing;
    @BindView(R.id.rv_comment_nothing)
    ImageView rvCommentNothing;
    @BindView(R.id.tv_flag_2)
    TextView tvFlag2;
    @BindView(R.id.tv_kucun)
    TextView tvKucun;
    @BindView(R.id.iv_cart_icon)
    ImageView ivCartIcon;
    @BindView(R.id.rv_format)
    RecyclerView rvFormat;
    private String productId;
    List<Goods> goodsList = new ArrayList<>();
    Goods goods;
    boolean isBuy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_goods_details_activity);
        ButterKnife.bind(this);
        productId = getIntent().getStringExtra("productId");
        radioGroupDetails.check(R.id.radio_goods_details);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvFormat.setLayoutManager(linearLayoutManager);
        initData();

        rvGoodsImages.setLayoutManager(new LinearLayoutManager(mContext));
        radioGroupDetails.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_goods_details) {
                    if (imageList.size() > 0) {
                        GoodsImageAdapter goodsImageAdapter = new GoodsImageAdapter(mContext, imageList);
                        rvGoodsImages.setAdapter(goodsImageAdapter);
                        rvGoodsDescNothing.setVisibility(View.GONE);
                        rvGoodsImages.setVisibility(View.VISIBLE);
                    } else {
                        rvGoodsDescNothing.setVisibility(View.VISIBLE);
                        rvGoodsImages.setVisibility(View.GONE);
                    }
                    rvCommentNothing.setVisibility(View.GONE);
                    rvGoodsComment.setVisibility(View.GONE);
                } else {
                    rvCommentNothing.setVisibility(View.VISIBLE);
                    rvGoodsComment.setVisibility(View.GONE);
                    rvGoodsDescNothing.setVisibility(View.GONE);
                    rvGoodsImages.setVisibility(View.GONE);
                }
            }
        });
    }

    List<String> imageList = new ArrayList<>();
    private TextAdapter textAdapter;

    private void initData() {
        HttpUtils.get().url(AppConfig.STORE_GOODS_DETAILS)
                .params("productId", productId)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.getInteger("resultCode") == 1) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            goods = JsonTool.jsonToObject(jsonObject.getString("data"), Goods.class);
                            if (goods == null) {
                                return;
                            }
                            if (goods.getProductAlbum().contains(",")) {
                                imageList = Arrays.asList(goods.getProductAlbum().split(","));
                            } else {
                                imageList.add(goods.getProductAlbum());
                            }
                            banner.setAdapter(new BannerImageAdapter(StoreGoodsDetailsActivity.this, imageList))
                                    .setIndicator(new CircleIndicator(StoreGoodsDetailsActivity.this))
                                    .setOrientation(Banner.HORIZONTAL)
                                    .start();
                            if (imageList.size() > 0) {
                                Glide.with(mContext).load(imageList.get(0)).into(ivGoodsImage);
                                rvGoodsImages.setVisibility(View.VISIBLE);
                            } else {
                                rvGoodsDescNothing.setVisibility(View.VISIBLE);
                                rvGoodsImages.setVisibility(View.GONE);
                            }

                            List<String> descImages = new ArrayList<>();
                            if (TextUtils.isEmpty(goods.getProductDesc())) {
                                if (goods.getProductDesc().contains(",")) {
                                    descImages = Arrays.asList(goods.getProductDesc().split(","));
                                } else {
                                    descImages.add(goods.getProductDesc());
                                }
                                GoodsImageAdapter goodsImageAdapter = new GoodsImageAdapter(mContext, descImages);
                                rvGoodsImages.setAdapter(goodsImageAdapter);
                                rvGoodsDescNothing.setVisibility(View.GONE);
                            }
                            tvGoodsName.setText(goods.getProductName());
                            tvGoodsName2.setText(goods.getProductName());
                            if (!TextUtils.isEmpty(goods.getProductOrgiMoney())) {
                                tvGoodsPrice2.setText(String.format("￥%s", goods.getProductOrgiMoney()));
                                tvMarketPrice.setText(String.format("￥%s", goods.getProductOrgiMoney()));
                            } else {
                                tvMarketPrice.setText(String.format("￥%s", goods.getProductMoney()));
                                tvGoodsPrice2.setText(String.format("￥%s", goods.getProductMoney()));
                            }
                            tvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                            tvPrice.setText(String.format("￥%s", goods.getProductMoney()));

                            tvGoodsFlag.setText(String.format("规格：%s", goods.getProductWeight()));
//                            tvFlag2.setText(String.format("规格：%s", goods.getProductWeight()));
                            tvKucun.setText(String.format("库存：%s", goods.getProductNum()));
                           /* if (goods.getProductIsfree().equals("0")) {
                                tvGoodsTag.setVisibility(View.VISIBLE);
                            } else {
                                tvGoodsTag.setVisibility(View.GONE);
                            }*/
                            tvGoodsDetails.setText(goods.getProductText());
                            List<String> strings = new ArrayList<>();
                            strings.add(goods.getProductWeight());
                            textAdapter = new TextAdapter(mContext, strings);
                            textAdapter.setItemOnClickListener(new TextAdapter.ItemOnClickListener() {
                                @Override
                                public void onItemClick(String string, int position) {

                                    textAdapter.updateItem(position);
                                }
                            });
                            rvFormat.setAdapter(textAdapter);

                        }
                    });


                }

                Log.i("qin_store", result);
            }
        });
    }


    @OnClick({R.id.iv_back, R.id.iv_store_car, R.id.rl_add_cart, R.id.tv_add_cart, R.id.tv_buy
            , R.id.view_choose, R.id.iv_close_choose, R.id.tv_minus_num, R.id.tv_add_num, R.id.tv_choose_commit, R.id.tv_flag_2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_flag_2:
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_store_car:
            case R.id.rl_add_cart:
                //跳转到购物车
                startActivity(new Intent(StoreGoodsDetailsActivity.this, StoreCartActivity.class));
                break;
            case R.id.tv_add_cart:
                //添加购物车
                rlChoose.setVisibility(View.VISIBLE);
                isBuy = false;
//                ToastUtil.showToast(StoreGoodsDetailsActivity.this, "加入购物车");
                break;
            case R.id.tv_buy:
                //立即购买
                isBuy = true;
                rlChoose.setVisibility(View.VISIBLE);
                break;
            case R.id.view_choose:
            case R.id.iv_close_choose:
                //选择规格
                rlChoose.setVisibility(View.GONE);
                break;
            case R.id.tv_minus_num:
                if (goodsNum > 1) {
                    goodsNum--;
                    tvGoodsNum.setText(String.valueOf(goodsNum));
                }

                break;
            case R.id.tv_add_num:
                goodsNum++;
                tvGoodsNum.setText(String.valueOf(goodsNum));
                break;
            case R.id.tv_choose_commit:
                if (textAdapter != null) {
                    if (textAdapter.getSelectedPosition() < 0) {
                        ToastUtil.showToast(mContext, "请选择规格");
                        return;
                    }
                } else {
                    ToastUtil.showToast(mContext, "请选择规格");
                    return;
                }
                rlChoose.setVisibility(View.GONE);
                goods.setProductNum(tvGoodsNum.getText().toString().trim());
                goodsList.add(goods);

                if (isBuy) {
                    Intent intent_commit_order = new Intent(StoreGoodsDetailsActivity.this, StoreOrderCommitActivity.class);
                    intent_commit_order.putExtra("goods", (Serializable) goodsList);
                    intent_commit_order.putExtra("type", 0);
                    startActivity(intent_commit_order);
                } else {
                    addCart();
                }
                break;
        }
    }

    private void addCart() {
        Map<String, String> map = new HashMap<>();
        map.put("cartAtime", String.valueOf(System.currentTimeMillis()));
        map.put("productId", goods.getId());
        map.put("productName", goods.getProductName());
        map.put("productWeigh", goods.getProductWeight());
        map.put("productLogo", goods.getProductLogo());
        map.put("productMoney", goods.getProductMoney());
        map.put("productNum", tvGoodsNum.getText().toString().trim());
        map.put("userId", getUser().getUserId());

        HttpUtils.get().url(AppConfig.STORE_ADD_CART)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.getInteger("resultCode") == 1) {
                    getCartNum();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TipDialog tipDialog = new TipDialog(StoreGoodsDetailsActivity.this);
                            tipDialog.setmConfirmOnClickListener("成功添加购物车", new TipDialog.ConfirmOnClickListener() {
                                @Override
                                public void confirm() {
                                    tipDialog.dismiss();
                                }
                            });
                            tipDialog.show();
                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(StoreGoodsDetailsActivity.this, "加入购物车失败");
                        }
                    });
                }
            }
        });
    }

    private void getCartNum() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", getUser().getUserId());

        HttpUtils.get().url(AppConfig.STORE_GET_CART_NUM)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.getInteger("resultCode") == 1) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            {"currentTime":1614653978350,"data":"103","resultCode":1}
                            if (jsonObject.containsKey("data")) {
                                int num = jsonObject.getInteger("data");
                                tvCartNum.setText(String.valueOf(num));
                            }

                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(StoreGoodsDetailsActivity.this, "购物车数量查询失败");
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCartNum();
    }
}
